function ProviderCtrl($scope, $http, $compile) {
	$scope.formCondition = {};
	$scope.unbindWatch = [];
 
	Pagination.initialize("/provider/findPage", $scope, $http);
	
	$scope.createProvider = function () {
		$scope.mode = 'create';
		$scope.editingProvider = {
			name: null,
			description: null
		};
		
		$scope.showModalForm();
	};
	
	$scope.editProvider = function (provider) {
		$scope.mode = 'update';
		$scope.editingProvider = Object.clone(provider);
		
		$scope.showModalForm();
	};
	
	$scope.showModalForm = function(){
		$scope.unbindWatch.push($scope.$watch('editingProvider.name', function(newValue, oldValue) {
			$scope.providerForm.name.$setValidity('duplicated', true);
		}));
		
		$('#modalPanel').modal('show');
	};
	
	$scope.saveProvider = function() {
		if ($scope.providerForm.$invalid) {
			return false;
		}
		
		$http.post("/provider/"+$scope.mode, $scope.editingProvider).success(function(response) {
			if (response.success) {
				$scope.closeModal();
				$scope.search();
			} else {
				if (response.result == 101) {
					// 101: provider name duplicated
					$scope.providerForm.name.$setValidity('duplicated', false);
				} else {
					$scope.providerForm.globalErrorMsg = response.message || "保存供应商失败！";
				}
			}
		});
	};
	
	$scope.closeModal = function(){
		$scope.providerForm.$setPristine();
		
		if($scope.unbindWatch && $scope.unbindWatch.length) {
			for (var i=0;i<$scope.unbindWatch.length;i++) {
				var call = $scope.unbindWatch[i];
				if (call) {
					call();
				}
			}
		}
		
		$scope.providerForm.globalErrorMsg = undefined;
		
		$('#modalPanel').modal('hide');
	};
	
	$scope.deleteProvider = function (provider) {
		Message.confirm("确认", "确认要删除供应商“" + provider.name + "”？", function () {
			$http.post("/provider/delete/" + provider.id).success(function (response) {
				if (response.success) {
					$scope.search();
				} else {
					Message.error("错误", response.message || "删除失败！");
				}
			});
		});
	};
	
	$scope.init = function() { 
		$scope.search();
	};
 
	$scope.init();
};

app.controller('ProviderCtrl', ProviderCtrl);